//
//  IGBatchRequestGroup.m
//  jingdongfang
//
//  Created by BOE on 2018/5/3.
//  Copyright © 2018年 BOE-SBG-CTO. All rights reserved.
//

#import "IGBatchRequestGroup.h"

@interface IGBatchRequestGroup()

@property (nonatomic, strong) NSArray *baseRequestArr;

@end

@implementation IGBatchRequestGroup

- (void)startWithBaseRequest:(NSArray<IGBaseRequest *> *)baseRequestArr decodeClassArr:(NSArray<Class> *)decodeClassArr CompletionBlockWithSuccess:(IGBatchRequestQueueCompletionBlock)completion {
    _baseRequestArr = baseRequestArr;
    self.resultStatus = IGRequestGroupStatusInit;
    
    dispatch_group_t group = dispatch_group_create();
    for (int i = 0; i < baseRequestArr.count; i++) {
        IGBaseRequest *request = baseRequestArr[i];
        Class decodeClass = decodeClassArr[i];
        __block NSInteger index = i;
        dispatch_group_enter(group);
        [request startWithDecodeClass:decodeClass CompletionBlockWithSuccess:^(id responseObject, NSError *error) {
            completion(responseObject, index, error, NO);
            
            dispatch_group_leave(group);
        }];
    }
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        completion(nil, -1, nil, YES);
    });
}

- (IGRequestGroupStatus)getResultStatus {
    for (IGBaseRequest *baseRequest in self.baseRequestArr) {
        if (baseRequest.resultStatus <= 2) { ///> Init/ Start/ Success
            _resultStatus = MIN(self.resultStatus, (IGRequestGroupStatus)baseRequest.resultStatus);
        } else {
            _resultStatus = IGRequestGroupStatusServerErr;
            break;
        }
    }
    return _resultStatus;
}

@end
